import commonAPI from '../../api/api'
var app = getApp();
var ba = wx.getBackgroundAudioManager();
const FN = require('../../utils/public');
import integralAPI from '../../api/integralAPI'
import collectionAPI from '../../api/collectionAPI'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    words:'',
    voiceSystemId:'',
    translationResult:{},
    usplayGif: "horn.png",
    playGif: "horn.png",
    pointsConfig: {},// 翻译積分配置
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.hideShareMenu(); // 禁止分享 
      this.setData({
        words:options.words,
        voiceSystemId:options.voiceSystemId
      })
      this.vsTranslation();
      this.hasCollectWord();
  },

  // 查询翻译
  vsTranslation(){
    var that = this;
    const item = app.globalData.miniappInfo.pointsconfigList.find(item=>item.pointsConfigKey == 'translateLowScoreWords');
    this.setData({
      pointsConfig:item,
    })

    if(app.globalData.userInfo.integralObj.integralNum<this.data.pointsConfig.pointsConfigValue || app.globalData.userInfo.integralObj.integralNum==null){
      this.navigateToPointsPageForVideo(app.globalData.userInfo.integralObj.integralNum);
      return;
    }

    commonAPI.vsTranslation({ words: this.data.words.trim(),
      translationRecordReq:{
        translationRecordPlatform:'有道翻译',
        voiceSystemId:that.data.voiceSystemId,
        translationRecordTarget:this.data.words.trim(),
       translationRecordType:'1',
      }
     }).then(res => {
      if (res.code == '200') {
        let errorwordsObj = typeof res.data.resultJson == 'object' ? res.data.resultJson : JSON.parse(res.data.resultJson);
        if(res.data.deductPoints == 'true'){
          that.handlePerformLowScoreWordExercise();
        }
        that.setData({
          translationResult: errorwordsObj,
          wordcount: res.data.wordcount,
          translationResultWrap: 'block'
        })
        that.handlePerformLowScoreWordExercise();
      }
    })
  },

    // 翻译积分消耗
    handlePerformLowScoreWordExercise(){
      let that = this;
      integralAPI.performLowScoreWordExercise({
        integralId:app.globalData.userInfo.integralObj.integralId,
        integraldetail:{
          integralId:app.globalData.userInfo.integralObj.integralId,
          integralDetailType:that.data.pointsConfig.pointsConfigType,
          integralDetailDesc:that.data.pointsConfig.pointsConfigName,
          integralDetailNum:that.data.pointsConfig.pointsConfigType === "1" ? that.data.pointsConfig.pointsConfigValue : -that.data.pointsConfig.pointsConfigValue
        }
       }).then(res => {})
    },

  // 跳转观看视频获取积分页面
navigateToPointsPageForVideo(integralNum){
  let promise = FN.Confirm(`积分不足，无法翻译，当前积分：${integralNum?integralNum:0}，看视频可以获取积分，是否观看？`);
  promise.then(res => {
    wx.navigateTo({
      url: '../myIntegral/myIntegral'
    })
  }).catch(res => {

  });
},

  // 英式发音
  ukVoice: function () {
    this.setData({
      playGif: "playGif.gif",
    })
    this.speech("uk-speech");
  },

  // 美式发音
  usVoice: function () {
    this.setData({
      usplayGif: "playGif.gif",
    })
    this.speech("us-speech");
  },

   // 语音合成
   textToSpeech(e) {
    var that = this;
    plugin4TSCY.textToSpeech({
      lang: "en_US",
      tts: true,
      content: e.currentTarget.dataset.words,
      success: function (res) {
        that.setData({
          textToSpeechFile: res.filename
        })
      },
      fail: function (res) {
        console.log("fail tts", res)
      }
    })
  },

   // 查询是否已收藏单词 Collection
   hasCollectWord: function () {
    var that = this;
    collectionAPI.hasCollectWord({ words: this.data.words }).then(res => {
      that.setData({
        wordcount: res.data.wordcount,
      })
    })
  },
// 收藏英语单词 
collWord: function (e) {
  var that = this, collectionContent = e.currentTarget.dataset.word;
  const data = {
    voiceSystemId: that.data.voiceSystemId,
    collectionContent: collectionContent,
    collectionType: "2"
  };
  commonAPI.colSaveCol({ ...data }).then(res => {
    if (res.code == '200') {
      that.setData({
        wordcount: 1,
      })
      FN.Toast("收藏成功");
    }
  })
},

// 取消收藏  
delWord: function (e) {
  var that = this;
  const data = { collectionContent: this.data.words };
  commonAPI.colDelCol({ ...data }).then(res => {
    if (res.code == '200') {
      that.setData({
        wordcount: 0,
      })
      FN.Toast(res.data);
    }
  })
},


 // 返回
 clostranslationResultWrap: function () {
  wx.navigateBack({
    delta: 0,
  })
},

speech: function (s) {
  var that = this;
  // var url =that.data.translationResult.basic[s] 
  var url =that.data.translationResult.speakUrl 
  ba.src = url
  ba.title = that.data.translationResult.query;
  ba.coverImgUrl = "-";
  ba.onPlay(function () {
    // that.setData({
    //   [btnObjState]: 1
    // })
  })

  // 监听播放是否已经结束
  ba.onEnded(function () {
    that.setData({
      playGif: "horn.png",
      usplayGif: "horn.png"
    })
  })

  // 监听背景音频停止事件
  ba.onError(function (res) {
    console.log(res)
    that.setData({
      playGif: "horn.png",
      usplayGif: "horn.png"
    })
  })

  // 监听背景音频暂停事件
  ba.onPause(function () {
    that.setData({
      playGif: "horn.png",
      usplayGif: "horn.png"
    })
  })

  // 监听背景音频停止事件
  ba.onStop(function () {
    that.setData({
      playGif: "horn.png",
      usplayGif: "horn.png"
    })
  })
}
})